package factory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class daoUtil {

    //Commit Teste

    private Connection conn = null;
    private static daoUtil daoUtil;
    private ArquivoConfig config;

    private daoUtil() {
        config = ArquivoConfig.getInstance();
    }

    public static daoUtil getInstance() {
        if (daoUtil == null) {
            daoUtil = new daoUtil();
            return daoUtil;
        }
        return daoUtil;
    }

    private Connection getConnexao() {
        try {
            Class.forName(config.getPropriedade("driver"));
            conn = DriverManager.getConnection(config.getPropriedade("url"), config.getPropriedade("user"), config.getPropriedade("senha"));

        } catch (ClassNotFoundException cnfe) {
            System.err.println("Driver not found\n" + cnfe);

        } catch (SQLException sqle) {
            System.err.println("Error ao criar a cconexão com o banco de dados\n");
            System.err.println("\nError Menssage: " + sqle.getMessage());
            System.err.println("\nError Cod.: " + sqle.getErrorCode());
            System.err.println("\nSQL State: " + sqle.getSQLState());

        } catch (Exception e) {
            System.err.println("Error\n" + e);
        }
        return conn;
    }

    public Statement getStatement() {
        Statement retorno = null;
        try {
            retorno = this.getConnexao().createStatement();
        } catch (SQLException ex) {
            Logger.getLogger(daoUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return retorno;
    }

    public PreparedStatement getPrepareStatemen(String sql) throws SQLException, Exception {

        return this.getConnexao().prepareStatement(sql);
    }
    
    public PreparedStatement getCallableStatemen(String sql) throws SQLException, Exception {
        return this.getConnexao().prepareCall(sql);
    }

    public void fecharTudo() {

        try {
            conn.close();
        } catch (Exception ex) {
            Logger.getLogger(daoUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
